package com.sany.taskmanager.ui.activity;

import static com.sany.taskmanager.global.Key.IntentKey.ACTIVITY_INDEX;

import android.content.Intent;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.zxing.Result;
import com.king.camera.scan.AnalyzeResult;
import com.king.camera.scan.CameraScan;
import com.king.camera.scan.analyze.Analyzer;
import com.king.zxing.BarcodeCameraScanActivity;
import com.king.zxing.DecodeConfig;
import com.king.zxing.analyze.MultiFormatAnalyzer;
import com.sany.taskmanager.R;
import com.sany.taskmanager.global.Constants;
import com.sany.taskmanager.global.Key;
import com.sany.taskmanager.util.LogUtil;
import com.sany.taskmanager.util.ToastUtil;

/**
 * 扫码页面
 */
public class ScanActivity extends BarcodeCameraScanActivity {

    @Override
    public void initCameraScan(@NonNull CameraScan<Result> cameraScan) {
        super.initCameraScan(cameraScan);
        // 是否播放提示音
        cameraScan.setPlayBeep(true);
    }

    @Nullable
    @Override
    public Analyzer<Result> createAnalyzer() {
        DecodeConfig config = new DecodeConfig();
        // 支持扫垂直的条码
        config.setSupportVerticalCode(true);
        // 支持识别反色码，黑白颜色反转
        config.setSupportLuminanceInvert(true);
        return new MultiFormatAnalyzer(config);
    }


    @Override
    public int getLayoutId() {
        return super.getLayoutId();
    }

    @Override
    public void onScanResultCallback(@NonNull AnalyzeResult<Result> result) {
        // 停止分析
        getCameraScan().setAnalyzeImage(false);
        // 处理扫码结果
        String resultStr = result.getResult().getText();
        LogUtil.d("resultStr = " + resultStr, ScanActivity.class);
        if (TextUtils.isEmpty(resultStr)) {
            ToastUtil.showToast(this, getString(R.string.tip_scan_empty));
            return;
        }
        String materialNum = resultStr.split("\\|")[0];
        LogUtil.d("materialNum = " + materialNum, ScanActivity.class);
        Intent intent = new Intent();
        int activityIndex = getIntent().getIntExtra(ACTIVITY_INDEX, Constants.ScanIndex.ACTIVITY_MAIN);
        if (activityIndex == Constants.ScanIndex.ACTIVITY_MAIN) {
            intent.setClass(this, MainActivity.class);
        } else if (activityIndex == Constants.ScanIndex.ACTIVITY_TASK) {
            intent.setClass(this, SendedTaskActivity.class);
        }
        intent.putExtra(Key.IntentKey.MATERIAL_NUM, materialNum);
        setResult(RESULT_OK, intent);
        finish();
        // 继续分析
//        getCameraScan().setAnalyzeImage(true);
    }

}
